//
// Created by jiang on 2021/12/30.
//

#include "scom.h"
#include "usart.h"
#include <stdio.h>
#include <stdarg.h>

#define RXBUF_SIZE (63)

uint8_t rx_buffer[RXBUF_SIZE] = {0};
uint8_t tx_buffer[RXBUF_SIZE] = {0};
uint8_t rx_len;


void SCOM_Init(void) {
    __HAL_UART_ENABLE_IT(&huart1, UART_IT_IDLE);
    HAL_UART_Receive_DMA(&huart1, rx_buffer, sizeof(rx_buffer) / sizeof(uint8_t));
    HAL_UART_Transmit_DMA(&huart1, tx_buffer, sizeof(tx_buffer) / sizeof(uint8_t));
}


void u_printf(const char *format, ...) {
    uint32_t length;
    va_list args;

    va_start(args, format);
    length = vsnprintf((char *) tx_buffer, sizeof(tx_buffer), (char *) format, args);
    va_end(args);
    HAL_UART_Transmit_DMA(&huart1, tx_buffer, length);
}

void SCOM_ReceiveHandler(void) {
    uint32_t temp;
    if ((__HAL_UART_GET_FLAG(&huart1, UART_FLAG_IDLE) != RESET)) {
        __HAL_UART_CLEAR_IDLEFLAG(&huart1);

        //Clear Status Register By Reading Status Register
        temp = huart1.Instance->ISR;

        //Clear Receive Complete Flag By Reading Data Register
        temp = huart1.Instance->RDR;

        HAL_UART_DMAStop(&huart1);

        //Get the remain Count of DMA Receive Buff
        temp = __HAL_DMA_GET_COUNTER(&hdma_usart1_rx);

        //Get the Count of DMA Received
        rx_len = RXBUF_SIZE - temp;

//        RCV_RingBuff_Write(rx_buffer, rx_len);

        //Start Receive again
        HAL_UART_Receive_DMA(&huart1, rx_buffer, RXBUF_SIZE);
    }
}

